package com.itheima.tlias.aspect;

import com.itheima.tlias.mapper.LogMapper;
import com.itheima.tlias.utils.BaseContext;
import com.itheima.tlias.pojo.OperationLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 通过 execution进行记录日志
 *
 * @Author mr.luo
 * @Date 18 4月 2025 10:47
 */
@Aspect
@Component
@Slf4j
public class OperationLogAspect1 {
    @Autowired
    private LogMapper logMapper;

    //切入点
    @Pointcut("execution(* com.itheima.tlias.controller.*.add(..)) " +
            "execution(* com.itheima.tlias.controller.*.delete(..)) " +
            "execution(* com.itheima.tlias.controller.*.update(..)) ")
    public void pt() {
    }

    //通知类型
    @Around("pt()")
    public Object optLogHandle(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        OperationLog operationLog = new OperationLog();
        //设置操作人id
        Integer id = BaseContext.get();
        operationLog.setOperateEmpId(id);
        //设置操作时间
        operationLog.setOperateTime(LocalDateTime.now());
        //获取类名
        String name = proceedingJoinPoint.getTarget().getClass().getName();
        operationLog.setClassName(name);
        //获取方法名
        String methodName = proceedingJoinPoint.getSignature().getName();
        operationLog.setMethodName(methodName);
        //获取方法的请求参数
        Object[] args = proceedingJoinPoint.getArgs();
        String s = Arrays.deepToString(args);
        operationLog.setMethodParams(s);

//        记录开始执行的时间
        long start = System.currentTimeMillis();
        //方法开始执行
        Object result = proceedingJoinPoint.proceed();
//        记录方法执行结束的时间
        long end = System.currentTimeMillis();

        String resultString = result.toString();
        operationLog.setReturnValue(resultString);

//        设置方法的耗时
        operationLog.setCostTime((end - start));
        log.info("我是OperationLogAspect1");
        log.info("要插入的数据是，{}",operationLog);
        //插入日志
        logMapper.insert(operationLog);

        //删除本地线程变量
        BaseContext.remove();
        return result;
    }
}
